// miniprogram/pages/admin/studio/studio.js
const app = getApp();
// const MAX_IMAGE_SIZE = 1024 * 1024 * 1024;
// const uploader = require('../../utils/upload.js');
const util = require("../../utils/util.js");
Page({

  removeImages: [],
  rules: {
    title: 'require',
    // slogan: 'require',
    // 'contact.wechat': 'require',
    //  'location.name': 'require',
    // 'contact.phone': 'require'
  },

  /**
   * 页面的初始数据
   */
  data: {
    studio: {

    },

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    wx.showNavigationBarLoading();
    app.login(user => {
      if (!user) {
        wx.navigateBack();
        return;
      }
      let isNew = !user.studio || options.op == 'new'
      that.setData({
        user,
        isNew
      })
      if (isNew) {
        wx.setNavigationBarTitle({
          title: '创建我的工作室',
        })
        that.setData({
          studio: {
            title: user.nickName + '的工作室',
            slogan: '[示例]留住美好瞬间',
            nodes: '<p>[示例]一直致力于学习孩子的简单 记录孩子的成长，每一张作品都是对童年的记录，温馨家庭生活的阐释，置身作品之外，却仿佛身在情境之中</p>'

          }
        })
      } else {
        that.setData({
          studio: user.studio
        })

      }
      //隐藏导航条加载动画
      wx.hideNavigationBarLoading();
      //停止下拉刷新
      wx.stopPullDownRefresh();
    });

  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.onLoad()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  isEditing(e) {
    console.log('isEditing', e.detail)
    this.setData({
      isEditing: e.detail.isEditing
    })
  },
  submitData: function (studio) {
    const that = this;
    wx.showLoading({
      title: '正在保存数据',
    });
    if (!studio._id) {
      let user = app.globalData.user;
      wx.cloud.callFunction({
        name: 'createStudio',
        data: {
          studio: studio,
          user: {
            nickName: user.nickName,
            avatarUrl: user.avatarUrl
          }
        },
        success: res => {
          wx.hideLoading();
          console.log(res.result);
          // 关联数据需要设置到user表中
          if (res.result.success) {

            if (res.result.studio._id) {
             // let pages = getCurrentPages();
              // app.relogin(user => {
              //   // if (pages.length > 1) {
              //   //   pages[pages.length - 2].onLoad();
              //   // }
              //   // wx.navigateBack();
              // })

              app.relogin(user => {
                wx.switchTab({                
                  url: '/pages/admin/index/index',
                })
              })

            }
          } else {
            wx.showToast({
              title: res.result.errMsg.errMsg,
              icon: 'none'
            })
          }
        },
        fail: err => {
          wx.hideLoading();
          console.log(err);
          wx.showToast({
            title: err.errMsg,
            icon: 'none'
          })
        }
      })
      this.loading = false;
    } else {
      wx.cloud.callFunction({
        name: 'crud',
        data: {
          op: 'update',
          table: 'studio',
          data: studio
        },
        success: res => {

          wx.hideLoading();
          let pages = getCurrentPages();
          app.relogin(user => {
            if (pages.length > 1) {
              pages[pages.length - 2].onLoad();
            }
            wx.navigateBack();
          })
          //app.globalData.user.studioid = res.result._id;
        }
      })
    }
  },

  apply: function (e) {
    // 需要防止重复点击
    // console.log(e);

    // if (!this.data.studio.cover || this.data.studio.cover.length == 0){
    //   wx.showModal({
    //     content: '请上传封面图片',
    //     showCancel: false
    //   })
    //   return;
    // }
    console.log(e.detail.value)
    let checkResult = util.checkForm(e.detail.value, this.rules);
    this.setData({
      errinfo: checkResult
    })
    if (Object.keys(checkResult).length != 0) {
      return;
    }

    const that = this;
    if (this.loading) return;
    this.loading = true;
    wx.showLoading({
      title: "正在准备数据"
    });
    let studio = this.data.studio;
    if (!studio) {
      studio = {}
    }
    for (var field in e.detail.value) {
      let nn = field.split('.');
      if (nn.length == 1) {
        studio[field] = e.detail.value[field]
      } else {
        if (!studio[nn[0]]) {
          studio[nn[0]] = {};
        }
        studio[nn[0]][nn[1]] = e.detail.value[field];
      }
      //  studio[field] = e.detail.value[field];
    }
    console.log(studio)
    if (studio._id) {
      studio.openid = app.globalData.user.openid;
      studio.nodes = this.selectComponent('#zEditor').data.nodes;
    }

    studio.create = {
      phone: this.data.user.phone,
      username: this.data.user.nickName
    }

    that.submitData(studio);

  },




  chooseImg: function (e) {
    const that = this;
    console.log(e)
    wx.navigateTo({
      url: '/pages/admin/gallary/gallary',
      success: res => {
        res.eventChannel.on('setImages', items => {

          if (items.length >= 1) {
            let id = e.currentTarget.id
            let nn = id.split('.');
            console.log(e.currentTarget.id, id, nn)
            if (nn.length == 1) {
              that.setData({
                [`studio.${id}`]: items[0]
              });
            } else {
              that.setData({
                [`studio.${nn[0]}.${nn[1]}`]: items[0]
                // [`studio.[nn[0]][${nn[1]]` :  items[0]              
              });

            }



          }
        });
        res.eventChannel.emit('setImages', {
          count: 1
        });
      }
    })
  },

  chooseLocation(e) {
    const that = this;
    var chooseParams = {
      success: function (res) {
        delete res.errMsg;
        that.setData({
          [`studio.location`]: res
        });
      },
      fail: err => {
        console.error(err);
      }
    };
    if (that.data.studio.location && that.data.studio.location.latitude) {
      chooseParams.latitude = that.data.studio.location.latitude;
      chooseParams.longitude = that.data.studio.location.longitude;
    }
    wx.getSetting({
      success(rr) {
        if (!rr.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              wx.chooseLocation(chooseParams);
            },
            fail() {
              wx.showModal({
                title: '提示',
                content: '您已拒绝小程序获取地理位置。如需打开，请点击右上角...图标，设置允许访问位置信息。',
                showCancel: false
              })
            }
          })
        } else {
          wx.chooseLocation(chooseParams)
        }
      }
    })

  },
  downloadFile: function (e) {
    console.log(e);
    let type = e.currentTarget.dataset.type;
    let url = e.currentTarget.dataset.url;
    switch (type) {
      case "pdf":
        url += 'pdf';
        break;
      case "word":
        url += 'docx';
        break;
      case "excel":
        url += 'xlsx';
        break;
      default:
        url += 'pptx';
        break;
    }
    wx.showLoading({

      title: '正在打开...',
    })
    wx.downloadFile({
      url: url,
      header: {},
      success: function (res) {
        var filePath = res.tempFilePath;
        console.log(filePath);
        wx.openDocument({
          filePath: filePath,
          success: function (res) {
            console.log('打开文档成功')
            wx.hideLoading()
          },
          fail: function (res) {
            console.log(res);
          },
          complete: function (res) {
            console.log(res);
          }
        })
      },
      fail: function (res) {
        console.log('文件下载失败');
      },
      complete: function (res) {},
    })
  },

})